package com.group18.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.group18.entity.FamilyUser;
import com.group18.service.AccountUserService;
import com.group18.service.FamilyUserService;
import com.group18.service.MemberUserService;


/**
 * Servlet implementation class DoDeleteFamily
 */
@WebServlet("/DoDeleteFamily")
public class DoDeleteFamily extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DoDeleteFamily() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		
		int id = Integer.parseInt(request.getParameter("id"));//家庭id
		
		//删除家庭
		FamilyUser fu = new FamilyUser();
		fu.setId(id);
		FamilyUserService fus = new FamilyUserService();
		boolean bl = fus.deleteByID(id);
		
		//删除member中对应家庭的数据
		MemberUserService mus = new MemberUserService();
		mus.deleteMemberByFamily_id(id);

		//删除account中对应家庭的收支数据
		AccountUserService aus = new AccountUserService();
		aus.deleteAccountByFamily_id(id);

		String msg = "";
		if(bl) {
			msg = "删除成功";
			
		}else {
			msg = "删除失败";
		}
		request.setAttribute("msg", msg);
		
		HttpSession session = request.getSession();
		int family_id = (int)session.getAttribute("family_id");
		if(family_id == id ) {//若删除的家庭是自己的家庭则返回登陆页面
			//获得家庭列表
			List<FamilyUser> list = fus.selectAllUser();
			request.setAttribute("list", list);
			
			request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
		}else {//是否是经过搜索后的操作后的删除操作，若是则返回搜索后的页面
			String text = request.getParameter("text");
	        if(text != null && !text.equals("")) {
				request.setAttribute("text", text);
				request.getRequestDispatcher("/DoSearchFamliy").forward(request, response);
			}else {
				request.getRequestDispatcher("/ToFamily").forward(request, response);
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
